package alipay

import (
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"github.com/smartwalle/xid"
	"log"
	"net/http"
)

var client *alipay.Client

const (
	kAppId      = "2021000122662233"
	kPrivateKey = "MIIEowIBAAKCAQEAjrqbs7vZHObQdYWUEF27wHEX0npTowzFwrz5yyB0fwz2uuMPdbkKR1qyhYHPI+w2Iu13b+uaG0Zqr8++lti0mcr1gxtaqtpoYB8EF5OIMdWs9I2f9/Z8ArGFhAGOGj3gDsac6H3KOX0yUP73g+bZ8pygra80Br429SFpnKyrniA02TZqVS0PmTzMmkDs7InAkccRaOjxQuREqB0/ogzVC9FtVfIy9hmKB1msYC2p0R1N2Sd72DfnQe3g55gJV5waaaAxiCmR4phKjj9r7XiYGqX50/NksnZIy+data918n9l/sX8vQh4GBlD/xn1aXgmSgxlCpcdmUtTJ8pqHmxIbQIDAQABAoIBAAu4m2zJMm1DLz9Xdu9ZI0AMiY5JaXDsbZkud70Mr0R3xhNW7kAWsBdoBV0daetjTJbVtYdFa+RthflmMBqnNT2kA0F/D5UUVpn+MhHVlcux5oA22To9zbVS6soKbqcNCcds3BnjqqXJ+EXaim0UmjVoU3Gv/6/GEzFSSyAIthdIImRAiqkbx/uO3uDPug4rIZRh7wztWBiFkNj24GnuL71B6zuJxliF6kd+JwNvCY6DAzmWdvEgzQYu5QKgd6krvuePJBmPcNVOlknhdEMgBtlaszQAjnRBWPeaCjk2bVjWRqT3AOE5VmFaLK/0/Cd8KvgGQg7vNjIYYBdOm6vsY+kCgYEAxkXpywXMriigzB7iyukIKOSNzSK23f89TPUDPtbahyop4wPg7q+25kduMYcZUSA6TmqyaFgsSz/mzvy3sPxjs/Wi13dIq5KvhX4XYhLkcnmjbiECqFNcZO1fYB2BifEAMO44i2wQ/s3wvklczoW2VsY2SE+qqpHT1g841hQvJgsCgYEAuEjEQT3BjbUormXvKvYJQzj+4fZEGgZnQlpbSw2qSAJ9wQwY+lfgjl+H2kjzw6QETnUhnsrtKPJVr/RRuoy3locb58d1YcIAAE7cToLyzfJegwIyWur0WZjxG6QKOIbjyVD5PAgV1vY5vUK9bpjHHcymKWvO//PXqH3BemyaLmcCgYAmRI4oMjlcD9lhLEDnmuyJP/uicSXMWRwSw2NZ+Iv69IdbGn+Kcf2iGn1JL+MSBl9ajTtb6lC6QV4h6yLlFQGFVU6VuZ8cBla8NCb9NdpDwfhqJBLoPBakIDB9U5SR9CLuTrw5JKVvGH5zq6Mu9R3JR75oXH/7JeQ194AnyYOEGwKBgGmu0V3Y3Lc3vSzGqHIqxwUWGpXbdRK3uWAEEXbpT04cn6GmHmzzGISNpIs6axE3boDQC4fVOEzTLPDLXFNvf5mDwi0Z5ec6KmYC07Tyw+v3otve1qHtPFRlsV/4oyPnt5osJcKXoG62pkYzkA9s7kPYqTH38a43WOX3uI1M2t7hAoGBAKhaec9Vl1HjAs2OuPYi4Mhd3IsBhIsALkh5WSffRePMATGw0Z/RRIjyFDHr8jqS8DXKsWnWw66NcpMJzhzM0XmGTjYxX292q5fogd5zeRbkFLcNayBAAtS1fPsb9/Z80eUuWiFZoQ6ubtcHHuHXhT7X17owwTweP2qmJTHVkZpC"
	kServerPort = "9989"
	// TODO 设置回调地址域名
	kServerDomain = ""
)

func init() {
	var err error

	if client, err = alipay.New(kAppId, kPrivateKey, false); err != nil {
		log.Println("初始化支付宝失败", err)
		return
	}

	// 加载证书
	if err = client.LoadAppCertPublicKeyFromFile("./etc/alipay/appPublicCert.crt"); err != nil {
		log.Println("加载证书发生错误", err)
		return
	}
	if err = client.LoadAliPayRootCertFromFile("./etc/alipay/alipayRootCert.crt"); err != nil {
		log.Println("加载证书发生错误", err)
		return
	}
	if err = client.LoadAlipayCertPublicKeyFromFile("./etc/alipay/alipayPublicCert.crt"); err != nil {
		log.Println("加载证书发生错误", err)
		return
	}

	if err = client.SetEncryptKey("vUNZcXSqubpXf/tKdzRnYA=="); err != nil {
		log.Println("加载内容加密密钥发生错误", err)
		return
	}
}

func Pay(orderID, price string) (string, error) {
	var tradeNo = fmt.Sprintf("%d", xid.Next())

	var p = alipay.TradePagePay{}
	p.NotifyURL = "http://6ffb522b.r2.cpolar.top/ali/notify"
	p.ReturnURL = "https://hezi-admin.threecats.cn/admin/auth/login"
	p.Subject = "支付测试:" + tradeNo
	p.OutTradeNo = orderID
	p.TotalAmount = price
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"
	url, err := client.TradePagePay(p)
	if err != nil {
		return "", err
	}
	fmt.Println(url.String())
	return url.String(), nil
}

func notify(writer http.ResponseWriter, request *http.Request) {
	request.ParseForm()

	var notification, err = client.DecodeNotification(request.Form)
	if err != nil {
		log.Println("解析异步通知发生错误", err)
		return
	}

	log.Println("解析异步通知成功:", notification.NotifyId)

	// 示例一：使用自定义请求进行查询
	var p = alipay.NewPayload("alipay.trade.query")
	p.AddBizField("out_trade_no", notification.OutTradeNo)

	var rsp *alipay.TradeQueryRsp
	if err = client.Request(p, &rsp); err != nil {
		log.Printf("异步通知验证订单 %s 信息发生错误: %s \n", notification.OutTradeNo, err.Error())
		return
	}
	if rsp.IsFailure() {
		log.Printf("异步通知验证订单 %s 信息发生错误: %s-%s \n", notification.OutTradeNo, rsp.Msg, rsp.SubMsg)
		return
	}

	log.Printf("订单 %s 支付成功 \n", notification.OutTradeNo)

	client.ACKNotification(writer)
}
